package jehc.djshi.oauth.web;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jehc.djshi.common.annotation.NeedLoginUnAuth;
import jehc.djshi.common.base.*;
import jehc.djshi.common.entity.OauthAccountEntity;
import jehc.djshi.common.entity.RoleinfoEntity;
import jehc.djshi.common.idgeneration.UUID;
import jehc.djshi.common.util.JsonUtil;
import jehc.djshi.common.util.StringUtil;
import jehc.djshi.oauth.model.*;
import jehc.djshi.oauth.service.*;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.github.pagehelper.PageInfo;

import javax.servlet.http.HttpServletRequest;
/**
 * @Desc 角色模块
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@RestController
@RequestMapping("/oauthRole")
@Api(value = "授权中心角色模块API",tags = "授权中心角色模块API",description = "授权中心角色模块API")
public class OauthRoleController extends BaseAction {
	@Autowired
	private OauthRoleService oauthRoleService;

	@Autowired
	private OauthSysModeService oauthSysModeService;
	/**
	* 加载初始化列表数据并分页
	* @param baseSearch
	*/
	@NeedLoginUnAuth
	@PostMapping(value="/list")
	@ApiOperation(value="查询角色列表并分页", notes="查询角色列表并分页")
	public BasePage getOauthRoleListByCondition(@RequestBody BaseSearch baseSearch, String del_flag ){
		Map<String, Object> condition = baseSearch.convert();
		condition.put("del_flag", del_flag);
		commonHPager(baseSearch);
		List<OauthRole> oauthRoleList = oauthRoleService.getOauthRoleListByCondition(condition);
		for(OauthRole oauthRole:oauthRoleList){
			if(!StringUtil.isEmpty(oauthRole.getCreate_id())){
				OauthAccountEntity createBy = getAccount(oauthRole.getCreate_id());
				if(null != createBy){
					oauthRole.setCreateBy(createBy.getName());
				}
			}
			if(!StringUtil.isEmpty(oauthRole.getUpdate_id())){
				OauthAccountEntity modifiedBy = getAccount(oauthRole.getUpdate_id());
				if(null != modifiedBy){
					oauthRole.setModifiedBy(modifiedBy.getName());
				}
			}
		}
		PageInfo<OauthRole> page = new PageInfo<OauthRole>(oauthRoleList);
		return outPageBootStr(page,baseSearch);
	}
	/**
	* 查询单个角色
	* @param role_id 
	*/
	@NeedLoginUnAuth
	@GetMapping(value="/get/{role_id}")
	@ApiOperation(value="查询单个角色", notes="查询单个角色")
	public BaseResult getOauthRoleById(@PathVariable("role_id")String role_id){
		OauthRole oauthRole = oauthRoleService.getOauthRoleById(role_id);
		if(!StringUtil.isEmpty(oauthRole.getCreate_id())){
			OauthAccountEntity createBy = getAccount(oauthRole.getCreate_id());
			if(null != createBy){
				oauthRole.setCreateBy(createBy.getName());
			}
		}
		if(!StringUtil.isEmpty(oauthRole.getUpdate_id())){
			OauthAccountEntity modifiedBy = getAccount(oauthRole.getUpdate_id());
			if(null != modifiedBy){
				oauthRole.setModifiedBy(modifiedBy.getName());
			}
		}
		return outDataStr(oauthRole);
	}
	/**
	* 添加
	* @param oauthRole 
	*/
	@PostMapping(value="/add")
	@ApiOperation(value="创建单个角色", notes="创建单个角色")
	public BaseResult addOauthRole(@RequestBody OauthRole oauthRole){
		int i = 0;
		if(null != oauthRole){
			oauthRole.setCreate_time(getDate());
			oauthRole.setRole_id(UUID.toUUID());
			i=oauthRoleService.addOauthRole(oauthRole);
		}
		if(i>0){
			return outAudStr(true);
		}else{
			return outAudStr(false);
		}
	}
	/**
	* 修改
	* @param oauthRole 
	*/
	@PutMapping(value="/update")
	@ApiOperation(value="编辑单个角色", notes="编辑单个角色")
	public BaseResult updateOauthRole(@RequestBody OauthRole oauthRole){
		int i = 0;
		if(null != oauthRole){
			oauthRole.setUpdate_time(getDate());
			i=oauthRoleService.updateOauthRole(oauthRole);
		}
		if(i>0){
			return outAudStr(true);
		}else{
			return outAudStr(false);
		}
	}
	/**
	* 删除
	* @param role_id 
	*/
	@DeleteMapping(value="/delete")
	@ApiOperation(value="删除角色", notes="删除角色")
	public BaseResult delOauthRole(String role_id){
		int i = 0;
		if(!StringUtil.isEmpty(role_id)){
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("role_id",role_id.split(","));
			i=oauthRoleService.delOauthRole(condition);
		}
		if(i>0){
			return outAudStr(true);
		}else{
			return outAudStr(false);
		}
	}

	/**
	 * 恢复
	 * @param role_id
	 * @return
	 */
	@PutMapping(value="/recover")
	@ApiOperation(value="恢复", notes="恢复")
	public BaseResult recoverOauthRole(String role_id){
		int i = 0;
		if(!StringUtil.isEmpty(role_id)){
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("role_id",role_id.split(","));
			i=oauthRoleService.recoverOauthRole(condition);
		}
		if(i>0){
			return outAudStr(true);
		}else{
			return outAudStr(false);
		}
	}
	@Autowired
	private OauthResourcesService oauthResourcesService;
	@Autowired
	private OauthFunctionInfoService oauthFunctionInfoService;
	@Autowired
	private OauthFunctionRoleService oauthFunctionRoleService;

	/**
	 * 读取所有资源
	 * @param request
	 */
	@NeedLoginUnAuth
	@GetMapping(value="/resources")
	@ApiOperation(value="读取所有资源", notes="读取所有资源")
	public BaseResult getOauthResourcesListAll(HttpServletRequest request){
		//1获取所有菜单
		Map<String, Object> condition = new HashMap<String, Object>();
		String role_id = request.getParameter("role_id");
		String sysmode_id = request.getParameter("sysmode_id");
		String expanded = request.getParameter("expanded");
		String singleClickExpand = request.getParameter("singleClickExpand");
		List<BaseZTreeEntity> list = new ArrayList<BaseZTreeEntity>();
		condition.put("resources_sys", "0");
		condition.put("sysmode_id", sysmode_id);
		List<OauthResources> oauthResourcesList = oauthResourcesService.getOauthResourcesListAll(condition);
		condition = new HashMap<String, Object>();
		condition.put("isfilter", "1");
		List<OauthFunctionInfo> oauthFunctionInfoList = oauthFunctionInfoService.getOauthFunctionInfoList(condition);
		//2获取所有已权限菜单
		condition.put("role_id", role_id);
		condition.put("sysmode_id", sysmode_id);
		List<OauthResources> oauthResourcesRoleList = oauthResourcesService.getOauthResourcesListAll(condition);
		String resources_id = resultOauthSourcesId(oauthResourcesRoleList);
		for(int i = 0; i < oauthResourcesList.size(); i++){
			OauthResources oauthResources = oauthResourcesList.get(i);
			BaseZTreeEntity BaseZTreeEntity = new BaseZTreeEntity();
			BaseZTreeEntity.setId(oauthResources.getResources_id());
			BaseZTreeEntity.setPId(oauthResources.getResources_parentid());
			BaseZTreeEntity.setText(oauthResources.getResources_title());
			BaseZTreeEntity.setName(oauthResources.getResources_title());
			if(resources_id.indexOf(oauthResources.getResources_id())<0){
				BaseZTreeEntity.setChecked(false);
			}else{
				BaseZTreeEntity.setChecked(true);
			}
//			if("0".equals(oauthResources.getResources_leaf())){
//				BaseZTreeEntity.setHasLeaf(false);
//			}else{
//				BaseZTreeEntity.setHasLeaf(true);
//				//当菜单为末级时判断是否存在功能
//				if(hasLeaf(oauthFunctionInfoList, oauthResources.getResources_id())){
//					BaseZTreeEntity.setHasLeaf(false);
//				}else{
//					BaseZTreeEntity.setHasLeaf(true);
//				}
//			}
//			BaseZTreeEntity.setIcon("../../../../deng/images/icons/"+xtMenuinfo.getXt_menuinfo_images());
			BaseZTreeEntity.setTempObject("Sources");
			if(("true").equals(expanded)){
				BaseZTreeEntity.setExpanded(true);
			}else{
				BaseZTreeEntity.setExpanded(false);
			}
			if("true".equals(singleClickExpand)){
				BaseZTreeEntity.setSingleClickExpand(true);
			}else{
				BaseZTreeEntity.setSingleClickExpand(false);
			}
			list.add(BaseZTreeEntity);
		}
		condition = new HashMap<String, Object>();
		condition.put("role_id", role_id.split(","));
		List<OauthFunctionRole> oauthFunctionRoleList = oauthFunctionRoleService.getOauthFunctionRoleListByCondition(condition);
		for(int i = 0; i < oauthFunctionInfoList.size(); i++){
			OauthFunctionInfo oauthFunctionInfo = oauthFunctionInfoList.get(i);
			BaseZTreeEntity BaseZTreeEntity = new BaseZTreeEntity();
			BaseZTreeEntity.setId(oauthFunctionInfo.getFunction_info_id()+"@"+oauthFunctionInfo.getMenu_id()+"@2");
			BaseZTreeEntity.setPId(oauthFunctionInfo.getMenu_id());
			BaseZTreeEntity.setText(oauthFunctionInfo.getFunction_info_name());
			BaseZTreeEntity.setName(oauthFunctionInfo.getFunction_info_name());
			BaseZTreeEntity.setIcon("/deng/images/icons/target_point.png");
			BaseZTreeEntity.setTempObject("Function");
			BaseZTreeEntity.setContent(""+oauthFunctionInfo.getFunction_info_name());
			BaseZTreeEntity.setIntegerappend(oauthFunctionInfo.getIsAuthority()+","+oauthFunctionInfo.getIsfilter());
			if(("true").equals(expanded)){
				BaseZTreeEntity.setExpanded(true);
			}else{
				BaseZTreeEntity.setExpanded(false);
			}
			if("true".equals(singleClickExpand)){
				BaseZTreeEntity.setSingleClickExpand(true);
			}else{
				BaseZTreeEntity.setSingleClickExpand(false);
			}
			for(OauthFunctionRole oauthFunctionRole:oauthFunctionRoleList){
				if(oauthFunctionRole.getFunction_info_id().equals(oauthFunctionInfo.getFunction_info_id())){
					BaseZTreeEntity.setChecked(true);
					break;
				}
			}
			BaseZTreeEntity.setHasLeaf(true);
			list.add(BaseZTreeEntity);
		}


		BaseZTreeEntity baseZTreeEntity = new BaseZTreeEntity();
		List<BaseZTreeEntity> baseZTreeEntityList = baseZTreeEntity.buildTree(list,"0");
		String json = JsonUtil.toFastJson(baseZTreeEntityList);
		return outStr(json);

//		return outStr(BaseZTreeEntity.buildTree(list,true));
	}

	/**
	 * 判断资源下面是否有功能
	 * @param oauthFunctionInfoList
	 * @param oauth_resources_id
	 * @return
	 */
	public boolean hasLeaf(List<OauthFunctionInfo> oauthFunctionInfoList,String oauth_resources_id){
		boolean flag = true;
		for(int i = 0; i < oauthFunctionInfoList.size(); i++){
			if(oauthFunctionInfoList.get(i).getMenu_id().equals(oauth_resources_id)){
				return true;
			}
		}
		flag = false;
		return flag;
	}

	/**
	 * 解析已有权限资源ID编号
	 * @param oauthResourcesList
	 * @return
	 */
	public String resultOauthSourcesId(List<OauthResources> oauthResourcesList){
		StringBuffer oauth_sources_id = new StringBuffer();
		for(int i = 0; i < oauthResourcesList.size(); i++){
			OauthResources oauthResources = oauthResourcesList.get(i);
			if(null != oauth_sources_id){
				oauth_sources_id.append(","+oauthResources.getResources_id());
			}else{
				oauth_sources_id.append(oauthResources.getResources_id());
			}
		}
		return oauth_sources_id.toString();
	}


	@Autowired
	private OauthResourcesRoleService oauthResourcesRoleService;
	/**
	 * 保存资源
	 * @param roleinfoEntity
	 */
	@PutMapping(value="/saveOauthRR")
	@ApiOperation(value="保存资源", notes="保存资源")
	public BaseResult saveOauthRR(@RequestBody RoleinfoEntity roleinfoEntity){
		int i = 0;
		List<OauthResourcesRole> oauthResourcesRoleList = new ArrayList<OauthResourcesRole>();
		List<OauthFunctionRole> oauthFunctionRoleList = new ArrayList<OauthFunctionRole>();
		if(!StringUtil.isEmpty(roleinfoEntity.getSources_id())){
			String[] idList = roleinfoEntity.getSources_id().split(",");
			for(int j = 0; j < idList.length; j++){
				if(idList[j].split("@").length == 1){
					//资源
					String uuid = UUID.toUUID();
					OauthResourcesRole oauthResourcesRole = new OauthResourcesRole();
					oauthResourcesRole.setResources_id(idList[j]);
					oauthResourcesRole.setResources_role_id(uuid);
					oauthResourcesRole.setRole_id(roleinfoEntity.getRole_id());
					oauthResourcesRoleList.add(oauthResourcesRole);
				}else{
					//功能
					String uuid = UUID.toUUID();
					OauthFunctionRole oauthFunctionRole = new OauthFunctionRole();
					oauthFunctionRole.setResources_id(idList[j].split("@")[1]);
					oauthFunctionRole.setFunction_role_id(uuid);
					oauthFunctionRole.setRole_id(roleinfoEntity.getRole_id());
					oauthFunctionRole.setFunction_info_id(idList[j].split("@")[0]);
					oauthFunctionRoleList.add(oauthFunctionRole);
				}
			}
		}
		i=oauthResourcesRoleService.addOauthResourcesRole(oauthResourcesRoleList,oauthFunctionRoleList,roleinfoEntity.getRole_id());
		if(i>0){
			return outAudStr(true, BaseUtils.getCacheStr("sys_import_sources_sucess"));
		}else{
			return outAudStr(false, BaseUtils.getCacheStr("sys_improt_sourcess_error"));
		}
	}


	@Autowired
	private OauthAccountRoleService oauthAccountRoleService;

	@Autowired
	private OauthAccountTypeService oauthAccountTypeService;
	/**
	 * 读取账户角色列表【账户对角色】
	 * @param baseSearch
	 */
	@NeedLoginUnAuth
	@PostMapping(value="/account/list")
	@ApiOperation(value="读取账户", notes="读取账户")
	public BasePage getAccountListByCondition(@RequestBody BaseSearch baseSearch){
		Map<String, Object> condition = baseSearch.convert();
		commonHPager(baseSearch);
		if(null != baseSearch.ConvertToMap().get("account_type_id")){
			condition.put("id", baseSearch.ConvertToMap().get("id"));
		}
		if("2".equals(condition.get("flag"))){
			//根据角色获取当前系统中隶属于其账户类型
			Map<String,Object> map = new HashMap<>();
			map.put("role_id",condition.get("role_id"));
			StringBuilder account_type_ids = new StringBuilder();
			List<OauthAccountType> oauthAccountTypes = oauthAccountTypeService.getAccountTypeListByRoleId(map);
			if(!CollectionUtils.isEmpty(oauthAccountTypes)){
				for(OauthAccountType oauthAccountType: oauthAccountTypes){
					if(StringUtils.isEmpty(account_type_ids.toString())){
						account_type_ids.append(oauthAccountType.getAccount_type_id());
					}else{
						account_type_ids.append(","+oauthAccountType.getAccount_type_id());
					}
				}
				condition.put("account_type_ids",account_type_ids.toString());
			}
		}
		List<OauthAccount> oauthAccountList = oauthAccountRoleService.getOauthARListByCondition(condition);
		PageInfo<OauthAccount> page = new PageInfo<OauthAccount>(oauthAccountList);
		return outPageBootStr(page,baseSearch);
	}

	/**
	 * 导入账户信息
	 * @param roleinfoEntity
	 */
	@NeedLoginUnAuth
	@PostMapping(value="/addOauthAR")
	@ApiOperation(value="导入账户信息", notes="导入账户信息")
	public BaseResult addOauthAR(@RequestBody RoleinfoEntity roleinfoEntity){
		List<OauthAccountRole> oauthAccountRoleList = new ArrayList<OauthAccountRole>();
		if(!StringUtil.isEmpty(roleinfoEntity.getAccount_id()) && !StringUtil.isEmpty(roleinfoEntity.getRole_id())){
			String[] idList = roleinfoEntity.getAccount_id().split(",");
			for(int j = 0; j < idList.length; j++){
				String uuid = UUID.toUUID();
				OauthAccountRole oauthAccountRole = new OauthAccountRole();
				oauthAccountRole.setAccount_id(idList[j]);
				oauthAccountRole.setAccount_role_id(uuid);
				oauthAccountRole.setRole_id(roleinfoEntity.getRole_id());
				oauthAccountRoleList.add(oauthAccountRole);
			}
		}
		int i=oauthAccountRoleService.addOauthAccountRole(roleinfoEntity,oauthAccountRoleList);
		if(i>0){
			return outAudStr(true, "导入账户成功！");
		}else{
			return outAudStr(false, "导入账户失败！");
		}
	}

	/**
	 * 移除账户信息
	 * @param roleinfoEntity
	 */
	@DeleteMapping(value="/delOauthAR")
	@ApiOperation(value="移除账户信息", notes="移除账户信息")
	public BaseResult delOauthAR(RoleinfoEntity roleinfoEntity){
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("account_id", roleinfoEntity.getAccount_id().split(","));
		condition.put("role_id", roleinfoEntity.getRole_id());
		int i=oauthAccountRoleService.delOauthAccountRole(condition);
		if(i>0){
			return outAudStr(true, "移除账户成功！");
		}else{
			return outAudStr(false, "移除账户失败！");
		}
	}

	/**
	 * 查询指定用户全部角色
	 * @param account_id
	 * @return
	 */
	@NeedLoginUnAuth
	@PostMapping(value="/roleList/{account_id}")
	@ApiOperation(value="查询指定用户全部角色", notes="查询指定用户全部角色")
	public BaseResult getOauthRoleList(@PathVariable("account_id")String account_id){
		if(StringUtil.isEmpty(account_id)){
			return new BaseResult();
		}
		Map<String,Object> condition = new HashMap<>();
		condition.put("account_id",account_id);
		List<OauthAccountRole>  oauthAccountRoles = oauthAccountRoleService.getOauthAccountRoleListByCondition(condition);
		if(!CollectionUtils.isEmpty(oauthAccountRoles)){
			for(OauthAccountRole oauthAccountRole:oauthAccountRoles){
				oauthAccountRole.setRole_name(oauthRoleService.getOauthRoleById(oauthAccountRole.getRole_id()).getRole_name());
			}
		}
		return new BaseResult(oauthAccountRoles);
	}


	/**
	 * 角色树
	 */
	@NeedLoginUnAuth
	@GetMapping(value="/trees")
	@ApiOperation(value="角色树列表", notes="角色树列表")
	public BaseResult getAllRoles(){
		Map<String,Object> condition = new HashMap<>();
		List<BaseJSTreeEntity> list = new ArrayList<BaseJSTreeEntity>();
		List<OauthRole> oauthRoles = oauthRoleService.getOauthRoleListByCondition(condition);

//		//1.筛选模块
//		List<OauthSysMode> oauthSysModes = oauthSysModeService.getOauthSysModeListByCondition(condition);
//		for(OauthSysMode oauthSysMode: oauthSysModes){
//			BaseJSTreeEntity baseJSTreeEntity = new BaseJSTreeEntity();
//			baseJSTreeEntity.setId(oauthSysMode.getSys_mode_id());
//			baseJSTreeEntity.setParent("0");
//			baseJSTreeEntity.setText(oauthSysMode.getSysname());
//			baseJSTreeEntity.setSingleClickExpand(true);
//			baseJSTreeEntity.setState(new BaseJSTreeStateEntity(false,false,false));
//			baseJSTreeEntity.setTempObject("SYSMODE");
//			list.add(baseJSTreeEntity);
//		}

		//2.筛选角色
		for(OauthRole oauthRole: oauthRoles){
			BaseJSTreeEntity baseJSTreeEntity = new BaseJSTreeEntity();
			baseJSTreeEntity.setId(oauthRole.getRole_id());
//			baseJSTreeEntity.setParent(oauthRole.getSysmode_id());
			baseJSTreeEntity.setParent("0");
			baseJSTreeEntity.setText(oauthRole.getRole_name());
			baseJSTreeEntity.setSingleClickExpand(true);
			baseJSTreeEntity.setTempObject("ROLE");
			list.add(baseJSTreeEntity);
		}
		BaseJSTreeEntity baseJSTreeEntity = new BaseJSTreeEntity();
		List<BaseJSTreeEntity> baseJSTreeEntitiesList = baseJSTreeEntity.buildTree(list,"0");
		return new BaseResult(JsonUtil.toFastJson(baseJSTreeEntitiesList));
	}

	/**
	 * 根据各种情况查找集合不分页（流程设计器中处理组 发起组等使用）
	 * @param role_id
	 * @return
	 */
	@NeedLoginUnAuth
	@GetMapping(value="/list/{role_id}")
	@ApiOperation(value="根据各种情况查找集合不分页", notes="根据各种情况查找集合不分页")
	public BaseResult getXtPostList(@PathVariable("role_id")String role_id){
		List<OauthRole> list = new ArrayList<OauthRole>();
		if(!StringUtil.isEmpty(role_id)){
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("role_id", role_id);
			list = oauthRoleService.getOauthRoleListByCondition(condition);
		}
		return  outItemsStr(list);
	}
}
